//
// Created by Administrator on 2023/11/17.
//
#include "iostream"
#include "cstring"
#include "queue"

using namespace std;

const int N = 1.5e5 + 10, INF = 0x3f3f3f3f;

int n, m;
int dist[N];
bool st[N];

int e[N], ne[N], h[N], w[N], idx;

//由于是pair<int, int> 类型，heap首先按照第一关键字进行排序，其次在按照第二关键字进行排序，因此堆顶的点一定是最小距离的点
typedef pair<int, int> PII;//存距离和对应结点编号

int add(int a, int b, int c) {
    e[idx] = b,w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

int dijkstra() {
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;//小根堆
    heap.push({0, 1});

    while (!heap.empty()) {

        PII t = heap.top();//去最小的边
        heap.pop();

        int id = t.second, distance = t.first;

        if (st[id]) continue;//这点已经确定过
        st[id] = true;

        //更新之后的每条边
        for (int i = h[id]; i != -1; i = ne[i]) {
            int j = e[i];
            //更新
            if (dist[j] > distance + w[i]) {
                dist[j] = w[i] + distance;
                heap.push({dist[j], j});//距离变小，入堆
            }

        }

        return dist[n] == INF ? -1 : dist[n];
    }
}

int main() {
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while (m--) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    cout << dijkstra();
}